package vcp.server.requesthandler;

import ocsf.server.ConnectionToClient;
import vcp.client.request.UpdateComplaintRequest;
import vcp.client.request.response.ResponseRequest;
import vcp.entity.Complaint;
import vcp.entity.ComplaintHistory;
import vcp.enums.ComplaintType.ComplaintStatus;
import vcp.server.DAO.ComplaintDAO;
import vcp.server.DAO.ComplaintHistoryDAO;
import vcp.server.interfaces.IServer;
import vcp.server.utility.Constants.TableNames;
import vcp.server.utility.SystemClock;
/**
 * 
 * @author VCP team
 *<p> class handles complaint request from client</p>
 */
public class UpdateComplaintRequestHandler extends RequestHandler <UpdateComplaintRequest>
{
	/**
	 * class constructor
	 * @param server
	 */
	public UpdateComplaintRequestHandler ( IServer server )
	{
		super(server);
	}

	@Override
	public void execute ( UpdateComplaintRequest request, ConnectionToClient client )
	{
		ComplaintDAO complaintDAO = new ComplaintDAO();
		Complaint complaint = request.getComplaint();

		if ( complaint.getStatus() == ComplaintStatus.PENDING )
		{
			complaintDAO.updateComplaintStatus(complaint.getID(), complaint.getStatus());
		}
		else if ( complaint.getStatus() == ComplaintStatus.CLOSED )
		{
			complaint.setHistory(true);
			complaintDAO.updateComplaintStatus(complaint.getID(), complaint.getStatus());
			complaintDAO.updateIsHistory(complaint.getID(), complaint.isHistory());

			ComplaintHistory complaintHistory = new ComplaintHistory();
			complaintHistory.setID(this.server.getGeneratedID(TableNames.COMPLAINT_HISTORY));
			complaintHistory.setComplaintID(complaint.getID());
			complaintHistory.setComplaintResolveText(complaint.getResolveText());
			complaintHistory.setComplaintResolveStatus(complaint.getComplaintResolve());
			complaintHistory.setRefundAmount(complaint.getAmountRefound());
			complaintHistory.setCloseDate(SystemClock.getClockInstance().getSystemDateTime());
			complaintHistory.setSiteEnum(complaint.getSiteEnum());

			ComplaintHistoryDAO complaintHistoryDAO = new ComplaintHistoryDAO();
			complaintHistoryDAO.save(complaintHistory);
		}

		this.sendResponseRefresh(complaint, client);
		this.sendResponse(new ResponseRequest(request.getRequestID(), complaint), client);
	}

}
